var express = require("express");
var router = express.Router();

const UserModel = require("../../models/UserModel");
const md5 = require("md5");
// 引入JWT
const jwt = require("jsonwebtoken");
const { atguigu } = require('../../config/config')

// 获取登录的内容
router.post("/login", (req, res) => {
  const { username, password } = req.body;
  UserModel.findOne(
    { username: username, password: md5(password) },
    (err, data) => {
      if (err) {
        res.json({
          code: "2001",
          msg: "数据库查询失败！",
          data: null,
        });
        return;
      }
      if (!data) {
        res.json({
          code: "2002",
          msg: "用户名或密码不存在！",
          data: null,
        });
        return;
      }
      // 创建当前用户的token
      const token = jwt.sign(
        {
          username,
          _id: data._id,
        },
        atguigu,
        {
          expiresIn: 60 * 60 * 24 * 7,
        }
      );
      // 登录成功响应
      res.json({
        code: "0000",
        msg: "登录成功！",
        data: token,
      });
    }
  );
});

// 退出登录
router.post("/logout", (req, res) => {});

module.exports = router;
